﻿using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using TestApplication.Domain.Models;

namespace TestApplication.WebApi.Controllers
{
    [RoutePrefix("api/stores")]
    public class StoresController : ApiController
    {
        private readonly UnitOfWork _unitOfWork;

        public StoresController(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        [Route("{storeId:int}/products")]
        public IQueryable<Product> GetProducts(int storeId)
        {
            return _unitOfWork
                .ProductRepository
                .AsQueryable
                .Where(it => it.StoreId == storeId);
        }

        [ResponseType(typeof (Store))]
        [Route("{id:int}/title")]
        public IHttpActionResult GetStore(int id)
        {
            var store = _unitOfWork.StoreRepository.
                                    AsQueryable
                                   .Where(it => it.Id == id)
                                   .Select(it => new { it.Title })
                                   .SingleOrDefault();

            if (store == null)
            {
                return NotFound();
            }

            return Ok(store.Title);
        }

        #region Dispose

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _unitOfWork.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion
    }
}